/**
 * Created by Scoot on 2017/4/14.
 */
var login = false;
var total = 0;
var min = 1;
var productId = '';
var _specArr = [],oldSpecArr=[];

changeNum();

post({
    url : "/isLogin",
    success : function(data){
        if(!data){
            login = false;
        }else{
            login = true;
        }
    }
});

//加入购物车
$(".c_main .btn").click(function(){
    if(isEmpty(_specArr)){
        if(login){
            if(total>0){
                post({
                    url:"/cart/save",
                    data:{productId:productId,specGroup:_specArr.toString(),num:$(".num .middle input").val()},
                    success:function(data){
                        $(".c_main").animate({"bottom":"-120%"},"500");
                        $(".cover").animate({"opacity":"0"},"500");
                        setTimeout(function(){
                            $(".c_container").css("display","none");
                        },500);
                        $(".success_alert").css("display","block");
                        setTimeout(function(){
                            $(".success_alert").css("display","none");
                        },3000);
                    }
                })
            }
        }else{
            go("/login/index.html");
        }
    }else{
        $(".select_alert").css("display","block");
        setTimeout(function(){
            $(".select_alert").css("display","none");
        },3000)
    }
});

function getProductDetail(){ //获取商品详情
    post({
        url:'/product/'+productId+'/detail',
        success:function(data){
            //console.log(data);
            dealProductData(data);
        }
    });
}

function dealProductData(data){

    $(".c_detail .img img").attr("src",SERVER_CONTEXT_PATH+"/load/picture/"+data.imageUrl);
    //规格
    var _spec = '';
    for(var k=0;k<data["specifications"].length;k++){
        _spec += '<li><p>'+data["specifications"][k]["name"]+'</p>';
        for(var n=0;n<data["specifications"][k]["specValues"].length;n++){
            _spec += '<span data-id="'+data["specifications"][k]["specValues"][n]["id"]+'">';
            _spec += ''+data["specifications"][k]["specValues"][n]["specValue"]+'</span>';
        }
        _spec += '</li>';
        _specArr.push('');
    }
    $(".specification ul").html(_spec);
    $(".c_detail .price").html('价格：<span>￥'+(data.retailPrice).toFixed(2)+'</span>');
    specification();

}

function addCart(){
    $(".add_cart").click(function(){
        productId = $(this).data("id");
        _specArr = [];
        getProductDetail();
        $(".visual").css("visibility","hidden");
        $(".c_main .btn").css({"opacity":"0.65","background-color":"#cccccc"});
        $(".c_container").css("display","block");
        $(".cover").animate({"opacity":"0.5"},"500");
        $(".c_main").animate({"bottom":"0%"},"500");
    });

    $(".c_main .close").click(function(){
        $(".c_main").animate({"bottom":"-120%"},"500");
        $(".cover").animate({"opacity":"0"},"500");
        setTimeout(function(){
            $(".c_container").css("display","none");
        },500)
    });
}



//选择规格
function specification(){
    var _arr = [];
    $(".specification li").each(function(i){
        _arr[i] = "";
        $(this).find("span").click(function(){
            if(!!$(this).hasClass("red_back")){
                $(this).removeClass("red_back");
                _arr[i] = "";
                _specArr[i] = '';
            }else{
                _arr[i] = $(this).text();
                $(this).addClass("red_back").siblings("span").removeClass("red_back");
                _specArr[i] = $(this).data("id");
            }
            showSpec(_arr);
            getPrice(_specArr);
        });
    });
}

function showSpec(arr){
    arr = removeItem(arr);
    var str = "请选择规格";
    if(arr.length != 0){
        str = '已选择';
        for(var i=0;i<arr.length;i++){
            str += " " + arr[i];
        }
    }
    $(".c_main .spec").text(str);
}

function getPrice(arr){
    var flag = true;
    for(var i=0;i<arr.length;i++){
        if(arr[i]==''){
            flag = false;
        }
    }
    if(flag){
        post({
            url:"/product/getProductSkuInfo",
            data:{productId:productId,specGroup:arr.toString()},
            success:function(data){
                total = data.merchantTotal;
                $(".c_detail .price").html('价格：<span>￥'+(data.price).toFixed(2)+'</span>');
                $(".c_detail .total").html('库存'+data.total+'件');
                $(".num input").val(min);
                $(".num span").text("(可购买 "+total+" 件)");
                $(".visual").css("visibility","visible");
                if(total>0){
                    $(".c_main .btn").css({"opacity":"1","background-color":"#ea540a"});
                }else{
                    $(".c_main .btn").css({"opacity":"0.65","background-color":"#cccccc"});
                }
            }
        })
    }else{
        $(".visual").css("visibility","hidden");
        $(".c_main .btn").css({"opacity":"0.65","background-color":"#cccccc"});
    }
}

function changeNum(){
    //数量加1
    $(".num .add").click(function(){
        var num = parseInt($(".num .middle input").val());
        $(".num .add,.num .minus").css("opacity","1");
        if(total<=0){
            $(".num .middle input").val(0);
        }else{
            if(num>=total){
                $(".num .middle input").val(total);
                $(".num .add").css("opacity","0.3");
            }else{
                $(".num .middle input").val(num+1);
            }
        }
    });

    //数量减1
    $(".num .minus").click(function(){
        var num = parseInt($(".num input").val());
        $(".num .minus").css("opacity","0.3");
        if(total<=0){
            $(".num .middle input").val(0);
        }else{
            if(num>min){
                $(".num input").val(num-1);
                if(num-min > 1){
                    $(".num .minus").css("opacity","1");
                }
            }else{
                $(".num input").val(min);
            }
        }

    });

    //输入数量
    $(".num input").blur(function(){
        if(total<=0){
            $(".num .middle input").val(0);
        }else{
            var _val = $(this).val();
            if(isNaN(_val)||_val<=min){
                $(this).val(min);
                $(".num .minus").css("opacity","0.3");
            }else{
                $(".num .minus").css("opacity","1");
                var num = parseInt($(this).val());
                if(num>=total){
                    $(this).val(total);
                    $(".num .add").css("opacity","0.3");
                }else{
                    $(this).val(Math.ceil(_val));
                    $(".num .add").css("opacity","1");
                }
            }
        }
    });
}


//移除数组的空元素
function removeItem(arr){
    var newArr=[];
    for(var i=0;i<arr.length;i++){
        if(arr[i] != ""){
            newArr.push(arr[i]);
        }
    }
    return newArr;
}

//判断数组是否有空元素
function isEmpty(arr){
    var flag = true;
    for(var i=0;i<arr.length;i++){
        if(arr[i] == ""){
            flag = false;
        }
    }
    return flag;
}